use crate::models::product_skus::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/product-skus", post(create))
        .route("/product-skus/:id", get(get_by_id))
        .route("/product-skus/:id", post(update))
        .route("/product-skus/:id/delete", post(delete))
        .route("/product-skus/by-product/:product_id", get(get_by_product))
        .route("/product-skus/by-code/:code", get(get_by_code))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let product_sku = product_skus::Model::create(&state.db, &params).await?;
    format::json(product_sku)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let product_sku = product_skus::Model::find_by_id(&state.db, &id).await?;
    format::json(product_sku)
}

async fn update(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let product_sku = product_skus::Model::find_by_id(&state.db, &id).await?;
    let active_model: product_skus::ActiveModel = product_sku.into();


    format::json(())
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let product_sku = product_skus::Model::find_by_id(&state.db, &id).await?;
    product_sku.delete(&state.db).await?;
    format::json(())
}

async fn get_by_product(
    State(state): State<AppContext>,
    axum::extract::Path(product_id): axum::extract::Path<String>,
) -> Result<Response> {
    let product_skus = product_skus::Model::find_by_product_id(&state.db, &product_id).await?;
    format::json(product_skus)
}

async fn get_by_code(
    State(state): State<AppContext>,
    axum::extract::Path(code): axum::extract::Path<String>,
) -> Result<Response> {
    let product_sku = product_skus::Model::find_by_code(&state.db, &code).await?;
    format::json(product_sku)
}
